<template>
  <div>
    <el-container class="home-container">
      <el-header class="el-header">
        <TopBar />
      </el-header>
      <el-container class="el-container">
        <el-aside width="200px">
          <LeftBar />
        </el-aside>
        <el-main>
          <canvas ref="canvas" class="canvas" @mousedown="startDrawing" @mousemove="draw" @mouseup="finishDrawing"></canvas>
          <button @click="saveImage">保存</button>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import TopBar from '@/components/TopBar'
import LeftBar from '@/components/LeftBar'

export default {
  name: 'DrawingBoard',
  components: { TopBar, LeftBar },
  data () {
    return {
      isDrawing: false,
      lastX: 0,
      lastY: 0,
      ctx: null,
      pointList: [] // 存储点序列
    }
  },
  mounted () {
    this.ctx = this.$refs.canvas.getContext('2d')
    this.ctx.fillStyle = 'white'
    this.ctx.fillRect(0, 0, this.$refs.canvas.width, this.$refs.canvas.height)
  },
  methods: {
    startDrawing (event) {
      this.isDrawing = true
      this.lastX = event.clientX - this.$refs.canvas.offsetLeft
      this.lastY = event.clientY - this.$refs.canvas.offsetTop
      this.pointList.push([0, 0, 1]) // 在开始绘画时添加一个记录点
    },
    draw (event) {
      if (this.isDrawing) {
        const currentX = event.clientX - this.$refs.canvas.offsetLeft
        const currentY = event.clientY - this.$refs.canvas.offsetTop

        this.ctx.beginPath()
        this.ctx.moveTo(this.lastX, this.lastY)
        this.ctx.lineTo(currentX, currentY)
        this.ctx.stroke()

        this.pointList.push([currentX - this.lastX, currentY - this.lastY, 1]) // 添加绘画中的记录点

        this.lastX = currentX
        this.lastY = currentY
      }
    },
    finishDrawing () {
      this.isDrawing = false
      this.pointList.push([0, 0, 0]) // 在结束绘画时添加一个记录点
    },
    saveImage () {
      const dataUrl = this.$refs.canvas.toDataURL('image/png')
      const link = document.createElement('a')
      link.download = 'my-image.png'
      link.href = dataUrl
      link.click()

      this.savePoints() // 保存点序列为txt文件
    },
    savePoints () {
      const pointsString = this.pointList.map(point => point.join(',')).join('\n')
      const blob = new Blob([pointsString], { type: 'text/plain' })
      const link = document.createElement('a')
      link.download = 'my-points.txt'
      link.href = URL.createObjectURL(blob)
      link.click()
    }
  }
}
</script>

<style scoped>
.home-container {
  height: 100%;
  width: 100%;
}
.el-header{
  padding-left: 0;
  margin-left: 0;
}
.canvas {
  border: 5px solid black;
}
</style>
